package club.gskj.gulimall.ware.service.impl;

import club.gskj.common.constant.PurchaseContant;
import club.gskj.gulimall.ware.entity.PurchaseDetailEntity;
import club.gskj.gulimall.ware.service.PurchaseDetailService;
import club.gskj.gulimall.ware.service.WareSkuService;
import club.gskj.gulimall.ware.vo.PurchaseItemDoneVo;
import club.gskj.gulimall.ware.vo.PurchaseDoneVo;
import club.gskj.gulimall.ware.vo.PurchaseMergeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.ware.dao.PurchaseDao;
import club.gskj.gulimall.ware.entity.PurchaseEntity;
import club.gskj.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.and(w -> {
            w.eq("status", 0)
                    .or()
                    .eq("status", 1);
        });
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 开启事务
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(PurchaseMergeVo purchaseMergeVo) {

        // 采购单id
        Long purchaseId = purchaseMergeVo.getPurchaseId();
        // 判断如果未选择采购单，自动生成新采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(PurchaseContant.PurchaseStatusEnum.CATERED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // TODO 当采购需求的状态不是 0,1时， 不能进行采购单合并操作

        // 采购需求
        List<Long> items = purchaseMergeVo.getItems();

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(item);
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(PurchaseContant.PurchaseDetailStatusEnum.ASSINGED.getCode());
            return entity;
        }).collect(Collectors.toList());
        // 修改采购需求
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        // 修改采购单时间
        this.updateById(purchaseEntity);
    }

    /**
     * @param ids 采购单 id
     * @return void
     * @author 康纳-connor
     * @creed: Talk is cheap,show me the code
     * @date 21.2.7 13:18
     * @Description
     */
    @Override
    public void receivedPurchase(List<Long> ids) {
        // 确认当前采购单是新建、已分配状态
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            // 过滤 新建、已分配
            if (item.getStatus() == PurchaseContant.PurchaseStatusEnum.CATERED.getCode()
                    ||
                    item.getStatus() == PurchaseContant.PurchaseStatusEnum.ASSINGED.getCode()
            ) {
                return true;
            }
            return false;
        }).map(item -> {
            // 修改状态为 已领取
            item.setStatus(PurchaseContant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        // 修改
        this.updateBatchById(purchaseEntityList);

        // 改变采购项状态
        purchaseEntityList.forEach(item -> {
            // 根据采购单id 查询对应的所有 采购项列表
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listDetailByPurchaseId(item.getId());

            List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntityList.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setStatus(PurchaseContant.PurchaseDetailStatusEnum.BUYING.getCode());
                entity.setId(purchaseDetailEntity.getId());
                return entity;
            }).collect(Collectors.toList());
            // 修改采购项信息
            purchaseDetailService.updateBatchById(detailEntityList);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        // 采购单id
        Long id = purchaseDoneVo.getId();

        // 改变采购单状态
        Boolean flag = true;

        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updateItems = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            // 判断是否采购成功
            if (item.getStatus() == PurchaseContant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                // 采购失败，设置flag为 false
                flag = false;
                purchaseDetailEntity.setStatus(PurchaseContant.PurchaseDetailStatusEnum.HASERROR.getCode());
            } else {
                // 采购成功。 进行库存操作
                purchaseDetailEntity.setStatus(PurchaseContant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 将成功采购进行入库
                PurchaseDetailEntity detailServiceById = purchaseDetailService.getById(item.getItemId());
                // 添加库存
                wareSkuService.addStock(detailServiceById.getSkuId(), detailServiceById.getWareId(), detailServiceById.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            // 将要修改的 item存入新集合
            updateItems.add(purchaseDetailEntity);
        }
        // 批量更新 采购需求
        purchaseDetailService.updateBatchById(updateItems);

        // 采购单信息修改
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        if (flag) {
            purchaseEntity.setStatus(PurchaseContant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(PurchaseContant.PurchaseStatusEnum.HASERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        // 修改采购单 状态
        this.updateById(purchaseEntity);
    }
}
